/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-22 15:09:03
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-03-25 11:21:09
 * @FilePath: \vite-project\src\components\common\TagInput.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Icon } from '@iconify/react/dist/iconify.js';
import { Input, InputRef, Space, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';

interface TagInputProps {
	maxSize?: number;
	value?: string[];
	onChange?: (value: string[] | undefined) => void;
}

export default (props: TagInputProps) => {
	const [inputVisible, setInputVisible] = useState(false);
	const [inputValue, setInputValue] = useState('');
	const inputRef = useRef<InputRef>(null);

	const showInput = () => {
		setInputVisible(true);
	};
	const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		setInputValue(e.target.value);
	};
	const handleInputConfirm = () => {
		if (inputValue && !props?.value?.includes(inputValue)) {
			props?.onChange?.([...(props.value || []), inputValue]);
		}
		setInputVisible(false);
		setInputValue('');
	};
	const handleClose = (removedTag?: string) => {
		const newTags = props?.value?.filter((tag: string) => tag !== removedTag);
		props?.onChange?.(newTags);
	};

	useEffect(() => {
		if (inputVisible) {
			inputRef.current?.focus();
		}
	}, [inputVisible]);
	return (
		<>
			{props?.value?.map((tag: string, index: number) => (
				<Tag className="mb-8px" key={index} onClose={() => handleClose(tag)} closable>
					{tag}
				</Tag>
			))}
			{inputVisible ? (
				<Input
					ref={inputRef}
					type="text"
					size="small"
					value={inputValue}
					onChange={handleInputChange}
					onBlur={handleInputConfirm}
					onPressEnter={handleInputConfirm}
					width={64}
					height={22}
					className="w-64px mb-8px"
				/>
			) : props?.maxSize && (props.value?.length || 0) >= props?.maxSize ? null : (
				<Tag icon={<Icon icon="ant-design:plus-outlined" />} onClick={showInput}>
					新增标签
				</Tag>
			)}
		</>
	);
};
